package cn.change360.newappchildrenenglish;

import android.app.Dialog;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.gesture.Gesture;
import android.gesture.GestureLibraries;
import android.gesture.GestureLibrary;
import android.gesture.GestureOverlayView;
import android.gesture.Prediction;
import android.graphics.drawable.BitmapDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.IOException;
import java.util.ArrayList;

import cn.change360.newappchildrenenglish.utils.FileUtil;

/*
* 学字母内容
* */

public class LetterShowActivity extends AppCompatActivity implements View.OnClickListener, GestureOverlayView.OnGesturingListener, GestureOverlayView.OnGesturePerformedListener {

    ImageButton topbar_back, btn_reading;
    GestureOverlayView mDrawGestureView;
    TextView topbar_title, show_msg;
    ImageView show_word;

    String word;

    //手势库
    GestureLibrary mLibrary;

    SoundPool soundPool;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_letter_show);
        word = getIntent().getStringExtra("word");

        soundPool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
        soundPool.load(this, R.raw.s_true, 1);
        soundPool.load(this, R.raw.s_false, 2);

        initView();

        //载入手势库
        mLibrary = GestureLibraries.fromRawResource(this, R.raw.gesture);
        if (!mLibrary.load()) {
            mDrawGestureView.setEnabled(false);
        }
        show_word.setImageDrawable(new BitmapDrawable(FileUtil.getImageFromAssetsFile(this, "letter/" + word.toLowerCase() + ".jpg")));
    }

    private void initView() {
        topbar_back = (ImageButton) findViewById(R.id.topbar_back);
        topbar_title = (TextView) findViewById(R.id.topbar_title);
        show_word = (ImageView) findViewById(R.id.show_word);
        show_msg = (TextView) findViewById(R.id.show_msg);

        btn_reading = (ImageButton) findViewById(R.id.btn_reading);
        mDrawGestureView = (GestureOverlayView) findViewById(R.id.gesture);

        topbar_title.setText("学字母“" + word + "”");
        topbar_back.setOnClickListener(this);
        btn_reading.setOnClickListener(this);

        //设置手势可多笔画绘制，默认情况为单笔画绘制
        mDrawGestureView.setGestureStrokeType(GestureOverlayView.GESTURE_STROKE_TYPE_MULTIPLE);
        //设置手势的颜色(蓝色)
        mDrawGestureView.setGestureColor(getResources().getColor(R.color.gestureColor));
        //设置还没未能形成手势绘制是的颜色(红色)
        mDrawGestureView.setUncertainGestureColor(getResources().getColor(R.color.ungestureColor));
        //设置手势的粗细
        mDrawGestureView.setGestureStrokeWidth(20);
        mDrawGestureView.setFadeOffset(2000);
        //绑定监听器
        mDrawGestureView.addOnGesturePerformedListener(this);
        mDrawGestureView.addOnGesturingListener(this);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.topbar_back:
                finish();
                break;
            case R.id.btn_reading:
                reading();
                break;
        }
    }

    private void reading() {
        AssetManager am = getAssets();
        AssetFileDescriptor afd;
        try {
            afd = am.openFd("raw/" + word + ".mp3");
            MediaPlayer mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onGesturePerformed(GestureOverlayView gestureOverlayView, Gesture gesture) {
        showScore(getScore(gesture) + 10);
        show_msg.setText("请参考上方笔画顺序书写");
    }


    Dialog mAlertDialog;

    //显示结果
    private void showScore(double score) {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_show_score, null);
        TextView score_msg = (TextView) dialogView.findViewById(R.id.score_msg);
        //LinearLayout star_box = (LinearLayout) view.findViewById(R.id.star_box);
        ImageView img_star1 = (ImageView) dialogView.findViewById(R.id.img_star1);
        ImageView img_star2 = (ImageView) dialogView.findViewById(R.id.img_star2);
        ImageView img_star3 = (ImageView) dialogView.findViewById(R.id.img_star3);
        if (score > 80) {
            playSound(1);
            img_star1.setVisibility(View.VISIBLE);
            img_star2.setVisibility(View.VISIBLE);
            img_star3.setVisibility(View.VISIBLE);
            score_msg.setText("真棒，写的非常好！");
        } else if (score > 65) {
            playSound(1);
            img_star1.setVisibility(View.VISIBLE);
            img_star2.setVisibility(View.VISIBLE);
            img_star3.setVisibility(View.GONE);
            score_msg.setText("还好，写得不错！");
        } else if (score > 50) {
            playSound(1);
            img_star1.setVisibility(View.VISIBLE);
            img_star2.setVisibility(View.GONE);
            img_star3.setVisibility(View.GONE);
            score_msg.setText("嗯~勉强可以啦！");
        } else {
            playSound(2);
            img_star1.setVisibility(View.GONE);
            img_star2.setVisibility(View.GONE);
            img_star3.setVisibility(View.GONE);
            score_msg.setText("再写一遍吧！");
        }
        Animation starAnimation = AnimationUtils.loadAnimation(this, R.anim.zoom_in);
        img_star1.startAnimation(starAnimation);
        img_star2.startAnimation(starAnimation);
        img_star3.startAnimation(starAnimation);
        dialogView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mAlertDialog.cancel();
            }
        });
        mAlertDialog = new Dialog(this, R.style.theme_dialog);
        mAlertDialog.setContentView(dialogView);
        mAlertDialog.show();
    }

    @Override
    public void onGesturingStarted(GestureOverlayView gestureOverlayView) {
        show_msg.setText("正在书写~");
    }

    @Override
    public void onGesturingEnded(GestureOverlayView gestureOverlayView) {
        show_msg.setText("请稍等~");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //移除绑定的监听器
        mDrawGestureView.removeOnGesturePerformedListener(this);
        mDrawGestureView.removeOnGesturingListener(this);
    }

    public double getScore(Gesture gesture) {
        ArrayList<Prediction> predictions = mLibrary.recognize(gesture);
        double max = predictions.get(0).score;
        int n = 0;
        double a = 0;
        double score;
        for (int i = 0; i < predictions.size(); i++) {
            if (predictions.get(i).name.equals(word.toLowerCase())) {
                a = predictions.get(i).score;
                n = i;
            }
        }
        double p = a / (a + 20);
        score = (int) (60 - (n * 5) + 20 * p + 20 * (a / max));
        return score;
    }

    private void playSound(int m) {
        soundPool.play(m, 1, 1, 0, 0, 1);
    }
}
